package com.boss.filter;

import com.alibaba.fastjson.JSONObject;
import com.boss.api.dto.ApiResultDTO;
import com.boss.common.service.ICommonService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * <br>Title:
 * <br>Description:
 * <br>Author:
 * <br>Date:
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    @Autowired
    private ICommonService iCommonService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String tokenid = httpServletRequest.getHeader("X-Token");
        if(StringUtils.isEmpty(tokenid)) {
            tokenid = httpServletRequest.getHeader("tokenid");
        }
        if (httpServletRequest.getServletPath().equals("/v2/health")||"InsertPaymentTicket".equals(tokenid)) {
            return true;
        }
        Map<String, Object> result = iCommonService.checkToken(tokenid);
        String rscode = result.get("rscode").toString();
        /**
         * 成功或失败的编码 （100000 成功，113001失败，113999登录过期）
         */

        if ("113999".equals(rscode)) {
            StringBuffer uri=httpServletRequest.getRequestURL();
           String ip=uri.substring(0,uri.lastIndexOf(":"));
            logger.info(httpServletRequest.getServletPath());
            logger.info("=============token登录过期=============");
            String r=result.get("data").toString();
            JSONObject job=JSONObject.parseObject(r);
            boolean flag=true;
            if(flag) {
                job.put("redirectPath", ip);
            }
            this.returnJson(httpServletResponse, rscode, r);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private void returnJson(HttpServletResponse response, String code, String data){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSONObject.toJSON(ApiResultDTO.error(code, data)));
        } catch (IOException e){
            logger.error("拦截器返回信息错误");
        } finally {
            if(writer != null){
                writer.close();
            }
        }
    }
}
